package com.defysoft.waukids.main;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.Data_Sharedpreferences.SF_Adnotice;
import com.defysoft.waukids.Data_Type.WK_STATE;
import com.defysoft.waukids.Data_Type.WK_TEACHER_STATE;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PagerSlidingTabStrip;
import com.defysoft.waukids.PagerSlidingTabStrip.IconTabProvider;
import com.defysoft.waukids.PublicConstant;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.defysoft.waukids.album.Album_Main_F;
import com.defysoft.waukids.calendar.Calendar_Main_F;
import com.defysoft.waukids.calendar.Calendar_Main_Program;
import com.defysoft.waukids.diary.DiaryDetailActivity;
import com.defysoft.waukids.diary.Diary_Main_F;
import com.defysoft.waukids.home.Home_Main_F;
import com.defysoft.waukids.message.Message_list_Activity;
import com.defysoft.waukids.notice.NoticeDetailActivity;
import com.defysoft.waukids.notice.Notice_Main_F;
import com.defysoft.waukids.slide.Main_Slide_Beacon;
import com.defysoft.waukids.slide.Main_Slide_Children;
import com.defysoft.waukids.slide.Main_Slide_Info;
import com.defysoft.waukids.slide.Main_Slide_Myprofile;
import com.defysoft.waukids.slide.Main_Slide_Option;
import com.defysoft.waukids.slide.Main_Slide_Trip;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class Main_MainFrame extends BaseActivity implements OnClickListener {
	Toolbar toolbar;
	ViewPager viewPager;
	PagerSlidingTabStrip pst;
	Main_Main_Adapter adapter;
	TextView title;
	TextView beaconmsg;
	ImageView nextbtn;
	ImageView backbtn;
	ImageView titleimg;
	View drawer;
	View message;
	String adnotice_check;
	long now = System.currentTimeMillis();
	Date date = new Date(now);
	SimpleDateFormat today = new SimpleDateFormat("yyyy-MM-dd");
	int previousPage =0;
	boolean previousPage_check= true;
	LinearLayout[] slidebar = new LinearLayout[7];
	DrawerLayout drawerLayout;
	public android.support.v4.app.Fragment fragment[] = new android.support.v4.app.Fragment[5];
	int[] tablista = { R.drawable.menu_home, R.drawable.menu_notice,
			R.drawable.menu_diary, R.drawable.menu_album,R.drawable.menu_cal };
	//,R.drawable.menu_cctv
	ArrayList<WK_TEACHER_STATE> teacher_state;
	ArrayList<WK_STATE> state;
	PublicSharedpreferences psf;
	
	SharedPreferences.Editor editor;
	public Data_Sharedpreferences.SF_Member member;
	public Data_Sharedpreferences.SF_Student student;
	public Data_Sharedpreferences.SF_Class class1;
	public Data_Sharedpreferences.SF_School school;
	public Data_Sharedpreferences.SF_Adnotice adnotice;
	public Sqlite_Connect sqlite_Connect;
	int rank = 0;
	boolean drawerCheck = false;
	ActionBarDrawerToggle toggle;
	boolean new_notice = false;
	boolean new_diary = false;
	boolean new_album = false;
	boolean check_tab = false;
	int bea_position = 0;
	// 이미지 세팅
	DisplayImageOptions options;
	ImageLoader imageLoader;
	// 백키2번눌렀을때 종료.
	BackPressCloseHandler backPressCloseHandler;
	int tab_position=0;
	private final int START_MAIN = 7;
	private final int FAIR_STUDENTDATA = 8;
	private final int FAIR_CLASSDATA = 9;
	private final int SUBSETTING = 10;
	private final int GETSTATE_SUCCESS = 6;
	private final int FAIL_ADD_LOG = 5;
	private final int SUCCESS_ADD_LOG = 4;
	private final int FAIL_CONNECT =3;
	private final int ADNOT_SUCCESS =2;
	private final int ADNOT_FAIL=11;
	Cursor cursor;
	void tabicon_change() {

		if (!member.Rank.equals("3")) {
			// 새로운글 체크
			if (sqlite_Connect.check_New_Massage()) {
				message.setBackgroundResource(R.drawable.message_new);
			} else {
				message.setBackgroundResource(R.drawable.message);
			}
		}

		/*if (sqlite_Connect.check_New_Diary()) {
			tablista[2] = R.drawable.menu_diary_new;
		} else {
			tablista[2] = R.drawable.menu_diary;
		}

		if (sqlite_Connect.check_New_Notice()) {
			tablista[1] = R.drawable.menu_notice_new;
		} else {
			tablista[1] = R.drawable.menu_notice;
		}

		if (sqlite_Connect.check_New_Photo()) {
			tablista[3] = R.drawable.menu_album_new;
		} else {
			tablista[3] = R.drawable.menu_album;
		}*/
			pst.notifyDataSetChanged();
		/*	if (check_tab) {
		}*/
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		tabicon_change();

		switch (arg0) {

		case START_STUDENT_CHANGE:
			if (arg1 == REFRESH_CODE) {
				Intent i = new Intent(this, Main_Intro.class);
				startActivity(i);
				finish();
			}
			break;
		case START_NOTICE:
			if (arg1 == REFRESH_CODE) {
				((Notice_Main_F) fragment[1]).setStartData();
			}
			break;
		case START_DIARY:
			if (arg1 == REFRESH_CODE) { // 5555 리프레시코드
				((Diary_Main_F) fragment[2]).setStartData();
			}
			break;
		case START_ALBUM:
			if (arg1 == REFRESH_CODE) { // 5555 리프레시코드
				((Album_Main_F) fragment[3]).setStartData();
			}
			break;
		case START_SLIDE_MYPROFILE:
			if (arg1 == REFRESH_CODE) { // 5555 리프레시코드
				startActivity(new Intent(this, Main_Intro.class));
				finish();
			}
			break;
		case START_SLIDE_CHILDREN: // 자녀 설정 후.
			if (arg1 == REFRESH_CODE) { // 5555 리프레시코드
				startActivity(new Intent(this, Main_Intro.class));
				finish();
			}
		case SLIDE_MEMBERSTUDENT_CONNECT: // 자녀 등록 후.
			if (arg1 == REFRESH_CODE) { // 5555 리프레시코드
				startActivity(new Intent(this, Main_Intro.class));
				finish();
			}
			break;

		}
	}
/*	@Override
	protected void onResume() {
		super.onResume();
		
	}
*/
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.main_mainframe_activity);
		backPressCloseHandler = new BackPressCloseHandler(this);
		drawer =(View)findViewById(R.id.MAIN_MAIN_DRAWER_SLIDE);
		psf = new PublicSharedpreferences(this);
		setToolbar();
		setImgSetting();
		setStartData();
		psf.setAdnotice();
		adnotice = new SF_Adnotice();
		adnotice = psf.getAdnotice();
		
		date = new Date(now);
		startNetwork(4);
		
		
		
		registerReceiver(mRefreshMainFrame, new IntentFilter(
				"com.defysoft.waukids.REFRESH"));

		registerReceiver(mNewfreshMainFrame, new IntentFilter(
				"com.defysoft.waukids.NEWFRESH"));
	}

	@Override
	public void onBackPressed() {
		// super.onBackPressed();
		drawerLayout.closeDrawer(drawer);
		if (!drawerCheck) {
		backPressCloseHandler.onBackPressed();
		}
	}

	@Override
	public void setStartData() {
		super.setStartData();

		setSpData();
		sqlite_Connect = new Sqlite_Connect(this);
		pst = (PagerSlidingTabStrip) findViewById(R.id.MAIN_MAIN_TAB);
		title = (TextView) findViewById(R.id.MAIN_MAIN_TITLE);
		title.setSelected(true);
		beaconmsg = (TextView) findViewById(R.id.MAIN_MAIN_MSG);
		nextbtn = (ImageView) findViewById(R.id.MAIN_MAIN_NEXT);
		backbtn = (ImageView) findViewById(R.id.MAIN_MAIN_BACK);
		titleimg = (ImageView) findViewById(R.id.MAIN_MAIN_TITLEIMG);
		message = findViewById(R.id.MAIN_MAIN_VIEW);
		slidebar[0] = (LinearLayout) findViewById(R.id.MAIN_MAIN_MYPROFILE);
		slidebar[1] = (LinearLayout) findViewById(R.id.MAIN_MAIN_CHILDREN);
		slidebar[2] = (LinearLayout) findViewById(R.id.MAIN_MAIN_OPTION);
		slidebar[3] = (LinearLayout) findViewById(R.id.MAIN_MAIN_BEACON);
		slidebar[4] = (LinearLayout) findViewById(R.id.MAIN_MAIN_TRIP);
		slidebar[5] = (LinearLayout) findViewById(R.id.MAIN_MAIN_STUDENT_CONNECT);
		slidebar[6] = (LinearLayout) findViewById(R.id.MAIN_MAIN_INFO);
		state = new ArrayList<WK_STATE>();
		teacher_state = new ArrayList<WK_TEACHER_STATE>();
		
		 		
	
		
		// 메세지 기능 사용하는 유치원만 보이게.
		if (school.Document.equals("0")) {
			message.setVisibility(View.VISIBLE);
		}
		
		//cctv기능
		if (school.Cctv.equals("1")) {
		}
		if (member.Rank.equals("3")) {
			title.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent i = new Intent(Main_MainFrame.this,
							Main_Student_Change.class);
					startForActivity(START_STUDENT_CHANGE, i);
				}
			});
			titleimg.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent i = new Intent(Main_MainFrame.this,
							Main_Student_Change.class);
					startForActivity(START_STUDENT_CHANGE, i);
				}
			});
			titleimg.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent i = new Intent(Main_MainFrame.this,
							Main_Student_Change.class);
					startForActivity(START_STUDENT_CHANGE, i);
				}
			});

		} else if (member.Rank.equals("1") ||member.Rank.equals("2")){
			titleimg.setVisibility(View.GONE);
		}
		message.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivityForResult(new Intent(Main_MainFrame.this,
						Message_list_Activity.class),PublicConstant.START_MESSAGE);
			}
		});
		if (member.Rank.equals("1")) {
			startDIal();
			rank = 1;
			setStartDisplay();
			startNetwork(3);
			title.setText(school.Name + "원장님");
			slidebar[0].setVisibility(View.VISIBLE);
			slidebar[2].setVisibility(View.VISIBLE);
			slidebar[6].setVisibility(View.VISIBLE);
		} else if (member.Rank.equals("2")) {
			startDIal();
			rank = 2;
			startNetwork(1);
			slidebar[0].setVisibility(View.VISIBLE);
			slidebar[2].setVisibility(View.VISIBLE);
			slidebar[4].setVisibility(View.VISIBLE);
			slidebar[6].setVisibility(View.VISIBLE);
		} else if (member.Rank.equals("3")) {
			rank = 3;
			startNetwork(2);
			slidebar[0].setVisibility(View.VISIBLE);
			slidebar[1].setVisibility(View.VISIBLE);
			slidebar[2].setVisibility(View.VISIBLE);
			slidebar[3].setVisibility(View.VISIBLE);
			slidebar[5].setVisibility(View.VISIBLE);
			slidebar[6].setVisibility(View.VISIBLE);
		}
		for (int i = 0; i < slidebar.length; i++) {
			slidebar[i].setOnClickListener(this);
		}

		if (!member.Rank.equals("3")) {
			// 새로운글 체크
			if (sqlite_Connect.check_New_Massage()) {
				message.setBackgroundResource(R.drawable.message_new);
			} else {
				message.setBackgroundResource(R.drawable.message);
			}
		}

	}

	public void setStartDisplay() {
		if (fragment[0] == null) {
			fragment[0] = new Home_Main_F();
		}
		fragment[1] = new Notice_Main_F();
		fragment[2] = new Diary_Main_F();
		fragment[3] = new Album_Main_F();
		fragment[4] = new Calendar_Main_F();
		//fragment[5] = new Cctv_Main_F();
		viewPager = (ViewPager) findViewById(R.id.MAIN_MAIN_PAGER);
		adapter = new Main_Main_Adapter(getSupportFragmentManager());
		viewPager.setOffscreenPageLimit(5);
		viewPager.setAdapter(adapter);
		pst.setViewPager(viewPager);
		pst.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {				
				//set the previous selected page to state_selected = false
				((LinearLayout)pst.getChildAt(0)).getChildAt(previousPage).setSelected(false);
		        //set the selected page to state_selected = true
		        ((LinearLayout)pst.getChildAt(0)).getChildAt(arg0).setSelected(true);
		        //remember the current page
		        previousPage=arg0;
				
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		//check_tab = true;
	
		//pst.notifyDataSetChanged();

	}

	public void setToolbar() {
		drawerLayout = (DrawerLayout) findViewById(R.id.MAIN_MAIN_DRAWER);
		toolbar = (Toolbar) findViewById(R.id.MAIN_MAIN_TOOLBAR);
		// toggle세팅.
		toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
				R.string.app_name, R.string.hello_world) {
			@Override
			public void onDrawerClosed(View drawerView) {
				super.onDrawerClosed(drawerView);
				drawerCheck = false;
			}

			@Override
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
				drawerCheck = true;
			}
		};
		drawerLayout.setDrawerListener(toggle);
	}

	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		switch (_message.what) {
		case SUBSETTING:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			setStartDisplay();
			if (rank == 2) {
				title.setText(class1.Name + "선생님");
			} else if (rank == 3) {
				title.setText(student.Name);
				imageLoader.displayImage(HTTP_URL_STUDENTPHOTO + student.Photo,
						titleimg, options, null);
				
				if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){
				startActivity(new Intent(this, Main_MainSettting.class)
						.putExtra("stu_code", student.Code));
				}else{
					Toast.makeText(this, "현재 기기의 버전은 지키미 서비스를 지원 하지 않습니다.", Toast.LENGTH_LONG).show();
				}
			}

			startNetwork(3);
			endDIal();
			break;
		case GETSTATE_SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}

			if (member.Rank.equals("3")) {
				if (state.size() == 0) {
					nextbtn.setVisibility(View.INVISIBLE);
					backbtn.setVisibility(View.INVISIBLE);
				}
			} else {
				if (teacher_state.size() == 0) {
					nextbtn.setVisibility(View.INVISIBLE);
					backbtn.setVisibility(View.INVISIBLE);
				}
			}

			bea_position = 0;
			if (state.size() > 0 || teacher_state.size() > 0) {
				nextbtn.setOnClickListener(this);
				backbtn.setOnClickListener(this);
				if (member.Rank.equals("3")) {
					beaconmsg.setText((state.size()-bea_position)+"."+state.get(bea_position).Sta_Message + " "
							+ state.get(bea_position).Sta_Date);
			/*	if(!state.get(bea_position).Sta_FK_Code.equals("0")){	
					beaconmsg.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(state.get(bea_position).Sta_Rank.equals(GCM_NOTIEC_CODE)){
								sqlite_Connect.delete_New_Notice(Integer.parseInt(state.get(bea_position).Sta_FK_Code));
								fragment_notify(1);
								Intent i  = new Intent(Main_MainFrame.this,NoticeDetailActivity.class);
								i.putExtra("PK_Not_Code", state.get(bea_position).Sta_FK_Code);
								startActivityForResult(i,PublicConstant.START_NOTICE_DETAIL);
							}
							if (state.get(bea_position).Sta_Rank.equals(GCM_DIARY_CODE)){
								sqlite_Connect.delete_New_Diary(Integer.parseInt(state.get(bea_position).Sta_FK_Code));
								fragment_notify(2);
								Intent i  = new Intent(Main_MainFrame.this,DiaryDetailActivity.class);
								i.putExtra("PK_Dia_Code", state.get(bea_position).Sta_FK_Code);
								startActivityForResult(i,PublicConstant.START_DIARY_DETAIL);
							}
							
						}
					});
				}*/
				} else{
					beaconmsg
							.setText((teacher_state.size()-bea_position)+"."+teacher_state.get(bea_position).Tea_Message
									+ " "
									+ teacher_state.get(bea_position).Tea_Date);
					/*if(!teacher_state.get(bea_position).Tea_FK_Code.equals("0")){
					beaconmsg.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if (teacher_state.get(bea_position).Tea_Rank.equals(GCM_MESSAGE_CODE)){
								sqlite_Connect.delete_New_Mas(Integer.parseInt(teacher_state.get(bea_position).Tea_FK_Code));
								Intent i  = new Intent(Main_MainFrame.this,Message_Detail_Activity.class);
								i.putExtra("PK_Mes_Code", teacher_state.get(bea_position).Tea_FK_Code);
								i.putExtra("Mes_Category", teacher_state.get(bea_position).Tea_Mes_Category);
								startActivityForResult(i, PublicConstant.START_MESSAGE);
							}
							
						}
					});
					}*/
				}
			} else {
				beaconmsg.setText("오늘 메세지가 없습니다.");
			}

			break;

		case FAIR_CLASSDATA:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			Toast.makeText(this, "반데이터를 불러오지 못했습니다.반의 정보를 확인해주세요",
					Toast.LENGTH_LONG).show();
			
			break;
		case FAIR_STUDENTDATA:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			Toast.makeText(this, "원생데이터를 불러오지 못했습니다.원생의 정보를 확인해주세요",
					Toast.LENGTH_LONG).show();
			startActivityForResult(new Intent(Main_MainFrame.this,
					Main_MemberStudent_Connect_A.class).putExtra(
					"PK_Mem_Email", member.Email), SLIDE_MEMBERSTUDENT_CONNECT);
			finish();
			break;
		
		case SUCCESS_ADD_LOG:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			sqlite_Connect.delete_Err_Log();
			break;
		
		case FAIL_ADD_LOG:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			break;
		
		case FAIL_CONNECT:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"MAIN_MAIN_FRAME", member.Email);
			break;
			
		case ADNOT_SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			
			if(adnotice_check.equals("1")){
				
			if(!adnotice.aDate.equals("2015-05-02") || adnotice.aDate.equals("") ){
				
				Intent i = new Intent(this,Main_Admin_Notice.class);	
					startActivity(i);
			}
			}else{
				
			}
			break;
		case ADNOT_FAIL:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			
			break;
		}
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case 1:
					getClassData();
					break;
				case 2:
					getStudentData();
					break;
				case 3:
					getStateData();
					break;
				case 4:
					getAdnoticeData();
					break;
				}
			}
		});
		firstThread.start();
	}

	public void getAdnoticeData(){
		
		try{
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL, "code="+CODE_ADNOTICE));
			if(jsonObject.getBoolean("success")){
				adnotice_check = jsonObject.getString("on");
			
				onNetworkCallback(ADNOT_SUCCESS, "");
			}else{
				onNetworkCallback(ADNOT_FAIL, "");
			}
		}catch(Exception ex){
			onNetworkCallback(FAIL_CONNECT, ex.toString()+" where getAdnotice()");
		}
		
	}
	
	public void getClassData() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_MAIN_MAIN_GETCLASS + "&class="
							+ member.Class));
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				jsonObject = new JSONObject(msg);
				editor = psf.getClass_edit();
				editor.putString(PublicSharedpreferences.SF_Class_Key.CODE,
						jsonObject.getString("PK_Cla_Code"));
				editor.putString(PublicSharedpreferences.SF_Class_Key.INFO,
						jsonObject.getString("Cla_Info"));
				editor.putString(PublicSharedpreferences.SF_Class_Key.NAME,
						jsonObject.getString("Cla_Name"));
				editor.putString(PublicSharedpreferences.SF_Class_Key.SCHOOL,
						jsonObject.getString("FK_Sch_Cla_Code"));
				editor.commit();
				psf.setClasssp();
				class1 = psf.getClasssp();
				onNetworkCallback(SUBSETTING, "");
			} else {
				onNetworkCallback(FAIR_CLASSDATA, "");
			}
		} catch (Exception e) {
			onNetworkCallback(FAIL_CONNECT, e.toString()+" where getClassData()");
		}
		;
	}

	public void getStudentData() {
		String stu = "";
		String cla = "";
		try {

			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_URL,
					"code="
							+ CODE_MAIN_MAIN_GETSTUDENT
							+ "&email="
							+ member.Email
							+ "&connect="
							+ (member.Connect.equals("1")
									|| member.Connect.equals("0") ? ""
									: member.Connect)));
			if (jsonObject.getBoolean("success")) {
				stu = jsonObject.getString("stu");
				cla = jsonObject.getString("cla");

				jsonObject = new JSONObject(stu);
				editor = psf.getStudent_edit();
				editor.putString(PublicSharedpreferences.SF_Student_Key.BIRTH,
						jsonObject.getString("Stu_Birth"));
				editor.putString(PublicSharedpreferences.SF_Student_Key.CLASS,
						jsonObject.getString("FK_Cla_Stu_Code"));
				editor.putString(PublicSharedpreferences.SF_Student_Key.CODE,
						jsonObject.getString("PK_Stu_Code"));
				editor.putString(PublicSharedpreferences.SF_Student_Key.EMAIL,
						jsonObject.getString("Stu_Email"));
				editor.putString(PublicSharedpreferences.SF_Student_Key.INFO,
						jsonObject.getString("Stu_Info"));
				editor.putString(PublicSharedpreferences.SF_Student_Key.NAME,
						jsonObject.getString("Stu_Name"));
				editor.putString(PublicSharedpreferences.SF_Student_Key.PHOTO,
						jsonObject.getString("Stu_Photo"));
				editor.putString(
						PublicSharedpreferences.SF_Student_Key.RAN_STUCODE,
						jsonObject.getString("Rand_PK_Stu_Code"));
				editor.putString(PublicSharedpreferences.SF_Student_Key.SCHOOL,
						jsonObject.getString("FK_Sch_Stu_Code"));
				editor.commit();
				psf.setStudentsp();
				student = psf.getStudentsp();

				
				editor = psf.getMember_edit();
				editor.putString(PublicSharedpreferences.SF_Member_Key.CLASS, jsonObject.getString("FK_Cla_Stu_Code"));
				editor.commit();
				psf.setMembersp();
				member = psf.getMembersp();
				
				jsonObject = new JSONObject(cla);
				editor = psf.getClass_edit();
				editor.putString(PublicSharedpreferences.SF_Class_Key.CODE,
						jsonObject.getString("PK_Cla_Code"));
				editor.putString(PublicSharedpreferences.SF_Class_Key.INFO,
						jsonObject.getString("Cla_Info"));
				editor.putString(PublicSharedpreferences.SF_Class_Key.NAME,
						jsonObject.getString("Cla_Name"));
				editor.putString(PublicSharedpreferences.SF_Class_Key.SCHOOL,
						jsonObject.getString("FK_Sch_Cla_Code"));
				editor.commit();
				psf.setClasssp();
				class1 = psf.getClasssp();
				onNetworkCallback(SUBSETTING, "");
			} else {
				onNetworkCallback(FAIR_STUDENTDATA, "");
			}
		} catch (Exception e) {
			onNetworkCallback(FAIL_CONNECT, e.toString()+" where getStudentData()");
		}
		;
	}

	void getStateData() {
		String code = "";
		if (member.Rank.equals("3")) {
			code = "code=" + CODE_MAIN_STATE_LOAD + "&FK_Stu_Gob_Sta_Code="
					+ student.Code + "&rank=" + member.Rank
					+ "&FK_Sch_Gob_Sta_Code=" + member.School;

		} else {
			code = "code=" + CODE_MAIN_STATE_LOAD + "&FK_Cla_Tea_Code="
					+ member.Class + "&rank=" + member.Rank
					+ "&FK_Sch_Gob_Sta_Code=" + member.School;
		}

		try {

			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					code));
			if (jsonObject.getBoolean("success")) {

				if (member.Rank.equals("3")) {
					state = JsonParser.state_list(jsonObject
							.getString("payload"));
				} else {
					teacher_state = JsonParser.teacher_state_list(jsonObject
							.getString("payload"));
				}

				onNetworkCallback(GETSTATE_SUCCESS, "");
			} else {
				onNetworkCallback(FAIR_STUDENTDATA, "");
			}
		} catch (Exception e) {
			onNetworkCallback(FAIL_CONNECT, e.toString()+" where getStateData()");
		}
	}

	class Main_Main_Adapter extends FragmentPagerAdapter implements
			IconTabProvider {

		public Main_Main_Adapter(FragmentManager fm) {
			super(fm);
			// TODO Auto-generated constructor stub
		}

		@Override
		public Fragment getItem(int arg0) {
			// TODO Auto-generated method stub
			return fragment[arg0];
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			int count = 0;
			
				
				count = tablista.length;
			
			return count;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public int getPageIconResId(int position) {
			// TODO Auto-generated method stub
			return tablista[position];
		}

	
		
		
	}

	public void setSpData() {

		psf = new PublicSharedpreferences(this);
		psf.setClasssp();
		psf.setMembersp();
		psf.setSchoolsp();
		psf.setStudentsp();
		member = psf.getMembersp();
		school = psf.getSchoolsp();
		/*
		 * student = psf.getStudentsp(); school = psf.getSchoolsp();
		 */
	}

	public void setImgSetting() {
		// 이미지 세팅.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
		imageLoader = ImageLoader.getInstance();

		options = new DisplayImageOptions.Builder().cacheInMemory(true)
		/* .imageScaleType(ImageScaleType.EXACTLY) */
		.cacheOnDisc(true).considerExifParams(true).build();
	}

	public void startForActivity(int code, Intent intent) {
		startActivityForResult(intent, code);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.MAIN_MAIN_MYPROFILE:
			startActivityForResult(
					new Intent(this, Main_Slide_Myprofile.class),
					START_SLIDE_MYPROFILE);
			break;
		case R.id.MAIN_MAIN_CHILDREN:
			startActivityForResult(new Intent(this, Main_Slide_Children.class),
					START_SLIDE_CHILDREN);
			break;
		case R.id.MAIN_MAIN_OPTION:
			startActivity(new Intent(this, Main_Slide_Option.class));
			break;
		case R.id.MAIN_MAIN_BEACON:
			startActivity(new Intent(this, Main_Slide_Beacon.class).putExtra(
					"stu_code", student.Code).putExtra("stu_name", student.Name));
			break;
		case R.id.MAIN_MAIN_TRIP:
			startActivity(new Intent(this, Main_Slide_Trip.class));
			break;
		case R.id.MAIN_MAIN_STUDENT_CONNECT:
			startActivityForResult(new Intent(this,
					Main_MemberStudent_Connect_A.class).putExtra(
					"PK_Mem_Email", member.Email), SLIDE_MEMBERSTUDENT_CONNECT);
			break;
		case R.id.MAIN_MAIN_INFO:
			startActivity(new Intent(this, Main_Slide_Info.class));
			break;
		case R.id.MAIN_MAIN_BACK:
			if (bea_position == 0) {

				if (member.Rank.equals("3")) {
					bea_position = (state.size() - 1);
					beaconmsg.setText((state.size()-bea_position)+"."+state.get(bea_position).Sta_Message + " "
							+ state.get(bea_position).Sta_Date);
				} else {
					bea_position = (teacher_state.size() - 1);

					beaconmsg
							.setText((teacher_state.size()-bea_position)+"."+teacher_state.get(bea_position).Tea_Message
									+ " "
									+ teacher_state.get(bea_position).Tea_Date);
				}
			} else {

				bea_position = (bea_position - 1);
				if (member.Rank.equals("3")) {
					beaconmsg.setText((state.size()-bea_position)+"."+state.get(bea_position).Sta_Message + " "
							+ state.get(bea_position).Sta_Date);
				} else {

					beaconmsg
							.setText((teacher_state.size()-bea_position)+"."+teacher_state.get(bea_position).Tea_Message
									+ " "
									+ teacher_state.get(bea_position).Tea_Date);
				}
			}
			break;
		case R.id.MAIN_MAIN_NEXT:
			if (member.Rank.equals("3")) {
				if (bea_position == (state.size() - 1)) {
					bea_position = 0;
					beaconmsg.setText((state.size()-bea_position)+"."+state.get(bea_position).Sta_Message + " "
							+ state.get(bea_position).Sta_Date);
				} else {
					bea_position = (bea_position + 1);
					beaconmsg.setText((state.size()-bea_position)+"."+state.get(bea_position).Sta_Message + " "
							+ state.get(bea_position).Sta_Date);
				}
			} else {
				if (bea_position == (teacher_state.size() - 1)) {

					bea_position = 0;
					beaconmsg
							.setText((teacher_state.size()-bea_position)+"."+teacher_state.get(bea_position).Tea_Message
									+ " "
									+ teacher_state.get(bea_position).Tea_Date);
				} else {
					bea_position = (bea_position + 1);

					beaconmsg
							.setText((teacher_state.size()-bea_position)+"."+teacher_state.get(bea_position).Tea_Message
									+ " "
									+ teacher_state.get(bea_position).Tea_Date);
				}
			}
			break;
		}
	}

	private final BroadcastReceiver mRefreshMainFrame = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {

			if (intent.getStringExtra("PUSH_SENDTYPE").equals(
					PublicConstant.GCM_NOTIEC_CODE)) {
				((Notice_Main_F) fragment[1]).startNetwork(1);
			} else if (intent.getStringExtra("PUSH_SENDTYPE").equals(
					PublicConstant.GCM_DIARY_CODE)) {
				((Diary_Main_F) fragment[2]).startNetwork(1);
			} else if (intent.getStringExtra("PUSH_SENDTYPE").equals(
					PublicConstant.GCM_PHOTO_CODE)) {
				((Album_Main_F) fragment[3]).startNetwork(1);
			}else if (intent.getStringExtra("PUSH_SENDTYPE").equals(PublicConstant.GCM_CALENDAR_CODE)){
				((Calendar_Main_Program)((Calendar_Main_F)fragment[4]).fragment[1]).startNetwork(1);
			}else if (intent.getStringExtra("PUSH_SENDTYPE").equals(PublicConstant.GCM_NOTIEC_CODE_NONNEW)){
				((Notice_Main_F) fragment[1]).startNetwork(1);
			}else if (intent.getStringExtra("PUSH_SENDTYPE").equals(PublicConstant.GCM_PHOTO_CODE_NONNEW)){
				((Album_Main_F) fragment[3]).startNetwork(1);
			}

			if (Integer.parseInt(intent.getStringExtra("PUSH_SENDTYPE")) < 30000) {
				tabicon_change();
				((Home_Main_F) fragment[0]).startNetwork(0);
				startNetwork(3);
			} else {
				((Home_Main_F) fragment[0]).startNetwork(2);
			}

		}
	};

	private final BroadcastReceiver mNewfreshMainFrame = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {

			if (intent.getStringExtra("PUSH_SENDTYPE").equals(
					PublicConstant.GCM_NOTIEC_CODE)) {
				/*Log.i("여기 왔으요", intent.getStringExtra("PK_Not_Code"));*/
				sqlite_Connect.delete_New_Notice(Integer.parseInt(intent.getStringExtra("PK_Not_Code")));
				fragment_notify(1);
				Intent i  = new Intent(Main_MainFrame.this,NoticeDetailActivity.class);
				i.putExtra("PK_Not_Code", intent.getStringExtra("PK_Not_Code"));
				startActivityForResult(i,PublicConstant.START_NOTICE_DETAIL);
				
			
			} else if (intent.getStringExtra("PUSH_SENDTYPE").equals(
					PublicConstant.GCM_DIARY_CODE)) {
				sqlite_Connect.delete_New_Diary(Integer.parseInt(intent.getStringExtra("PK_Dia_Code")));
				fragment_notify(2);
				Intent i  = new Intent(Main_MainFrame.this,DiaryDetailActivity.class);
				i.putExtra("PK_Dia_Code", intent.getStringExtra("PK_Dia_Code"));
				startActivityForResult(i,PublicConstant.START_DIARY_DETAIL);
			} 

		}
	};
	
	// 백키 2번 눌렀을때 종료.
	public class BackPressCloseHandler {

		private long backKeyPressedTime = 0;
		private Toast toast;

		private Activity activity;

		public BackPressCloseHandler(Activity context) {
			this.activity = context;
		}

		public void onBackPressed() {

				
			if (System.currentTimeMillis() > backKeyPressedTime + 2000) {
				backKeyPressedTime = System.currentTimeMillis();

				showGuide();
				return;
			}
			if (System.currentTimeMillis() <= backKeyPressedTime + 2000) {
				activity.finish();
				toast.cancel();
			}

		}

		public void showGuide() {
			toast = Toast.makeText(activity, "\'뒤로\'버튼을 한번 더 누르시면 종료됩니다.",
					Toast.LENGTH_SHORT);
			toast.show();
		}
	}
	
	public void fragment_notify(int a){
		if(a == 1){
		((Notice_Main_F)fragment[1]).adapter.notifyDataSetChanged();
		}
		if(a == 2){
			((Diary_Main_F)fragment[2]).adapter.notifyDataSetChanged();
		}
	}
}